package com.sky.controller.admin;

import com.aliyuncs.exceptions.ClientException;
import com.sky.result.Result;
import com.sky.utils.IMageUploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;

@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "文件上传通用接口")
public class CommonController {
    private final IMageUploadUtils imageUploadUtils;

    public CommonController(IMageUploadUtils imageUploadUtils) {
        this.imageUploadUtils = imageUploadUtils;
    }

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传：{}", file.getOriginalFilename());
        String imageUrl;
        try {
            imageUrl = imageUploadUtils.upload(Objects.requireNonNull(file.getOriginalFilename()), file.getBytes());
        } catch (Exception e) {
            // 上传失败
            return Result.error("上传失败");
        }
        // 上传成功
        return Result.success(imageUrl);
    }
}
